package server.utils;


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.RedisTemplate;

public class CacheUtils {
    final static TimedCache<String, Object> timedCache = CacheUtil.newTimedCache(51840000);
    public static RedisTemplate<String, Object> redisTemplate = null;

    public static void set(String key, Object val) {
        if (redisTemplate != null) {
            redisTemplate.opsForValue().set(key, val);
            return;
        }
        timedCache.put(key, val);
    }

    public static void setStr(String key, Object val) {
        if (val == null) {
            return;
        }
        if (val instanceof String) {
            set(key, val);
        } else {
            set(key, JSON.toJSONString(val));
        }
    }

    public static Object get(String key) {
        if (redisTemplate != null) {
            return redisTemplate.opsForValue().get(key);
        }
        return timedCache.get(key);
    }

    public static String getStr(String key) {
        Object obj = get(key);
        if (obj == null) {
            return "";
        } else {
            if (obj instanceof String) {
                return obj.toString();
            }
            return JSON.toJSONString(obj);
        }
    }


    public static void remove(String key) {
        if (redisTemplate != null) {
            redisTemplate.delete(key);
            return;
        }
        timedCache.remove(key);
    }
}
